'use strict';

const router = require('koa-router')();
const fs = require('fs');

// 1、遍历并处理 所有的路由定义文件



function getRouteFiles(filePath) {
    // 查找当前目录
    let tmpPath = filePath || __dirname;

    // 读取目录下所有文件或者文件夹
    let files = fs.readdirSync(tmpPath);
  
    let routeFiles = files.filter(item => {
        return item.endsWith('.js') && item !== 'index.js';
    });
    // 返回所有的路由定义文件
    return routeFiles;
}

function registerRoute(router, routeFiles) {
    // 遍历所有路由定义文件
    routeFiles.forEach(item => {
        // 拼接路由文件的完整路径
        let tmpPath = __dirname + '/' + item;
        // 引入路由定义模块/文件
        let obj = require(tmpPath);
       
        for (let key in obj) {
           
            let tmpArr=key.split(' ');
            let routeUrl = tmpArr[1];
            let routeMethod = tmpArr[0];
            let routeFunction = obj[key];
            if (routeMethod === 'get') {
                router.get(routeUrl, routeFunction);
            } else if (routeMethod === 'post') {
                router.post(routeUrl, routeFunction);
            } else if (routeMethod === 'put') {
                router.put(routeUrl, routeFunction);
            } else if (routeMethod === 'delete') {
                router.delete(routeUrl, routeFunction);
            } else {

            }
       
        }
    });
    return router.routes();
}

module.exports = function () {
    let routeFiles = getRouteFiles();
    let fn = registerRoute(router, routeFiles);
    return fn;
};